import Ember from 'ember';
// import { translationMacro as t } from "ember-i18n";
import CommonUtil from '../utils/common';
// import BaseBusiness from './business/base-business';
import _ from 'lodash/lodash';

export default Ember.Route.extend({
  breadCrumb: null, //不显示导航
  service_PageConstrut:Ember.inject.service("page-constructure"),
  service_notification:Ember.inject.service("notification"),
  modelPre: {},
  beforeModel(transition) {
    var _self = this;
    var sec = new Ember.RSVP.Promise(function (resolve, reject) {
      //登录入口,先从本地取得当前用户，如果没有则登录
      _self.get("store").query("localstorage/user",{filter:{"current":1}}).then(function (users) {
        console.log("users get.len:" + users.get("length"));
        if(users.get("length")===0){
          console.log("need login");
          transition.abort();
          _self.gotoLoginPage();
          reject();
          return;
        }
        var userEnt = users.get("firstObject");
        console.log("userData get", userEnt);
        if(userEnt.get('current')===1){
          _self.get("global_curStatus").setUser(userEnt);
        }
        console.log("get user role",_self.get("global_curStatus").getUser());
        _self.get("global_curStatus").login().then(function (userRtn) {
          console.log("userrtn in rol",userRtn);
          //再查一下user对象，异步查询
          _self.get("store").findRecord("user",userRtn.get("id"));
          resolve(userRtn);
        }, function (event) {
          //登录失败后跳转到登录页面
          console.log("reject and login");
          _self.transitionTo('user-login');
          reject(event);
        });
      });
    });
    return new Ember.RSVP.Promise(function (resolve, reject) {
      sec.then(function(){
        //返回菜单数据
        var curUser = _self.get("global_curStatus").getUser();
        console.log("curUser in:", curUser);
        //发送socket登录
        _self.get("service_notification").socketLogin();
        //通过用户的角色，查询对应的权限列表
        curUser.get("role").then(function (role) {
          console.log("role get:", role);
          //如果没有role，从服务器上取得角色以及权限信息并存本地
          var privPromise = null;
          if(!role){
            privPromise = new Ember.RSVP.Promise(function (resolve, reject) {
              _self.store.findRecord("user",curUser.get("id")).then(function(userRemote){
                console.log("userRemote:",userRemote);
                userRemote.get("role").then(function(roleRemote){
                  console.log("roleRemote:",roleRemote);
                  //保存到本地
                  _self.get("global_curStatus").saveRoleWithUser(roleRemote,curUser).then(function(roleEnt){
                    resolve(roleEnt.get("privileges"));
                  });
                });
              });
            });
          }else{
            privPromise = role.get("privileges");
          }
          console.log("privPromise:",privPromise);
          privPromise.then(function (privilegesIn) {
            //权限列表生成树形
            var voMenuTree = new Ember.A();
            var voFuncTree = new Ember.A();
            var i = 0;
            var len = privilegesIn.get("length");
            console.log("privilegesIn:", privilegesIn);
            console.log("len:", len);
            //数据处理，并判断是否需要resolve返回
            var endTransfer = function (voItem) {
              i++;
              console.log("voItem get:", voItem);
              //轮循结束后，转化为树形对象，并返回
              var oritext = voItem.text;
              //多语言转换
              //voItem.text = _self.get('i18n').t(oritext).string;
              //首先维护功能树
              voFuncTree.pushObject(voItem);
              //如果没有文字，则说明不是菜单
              if(!voItem.text){
                return;
              }
              var voItemCopy = jQuery.extend({}, voItem);
              //然后维护菜单树
              if(voItem.type===1){
                voMenuTree.pushObject(voItemCopy);
              }
              if (i >= len) {
                // voFuncTree = _.sortBy(voFuncTree, ["level","order"]);
                // voMenuTree = _.sortBy(voMenuTree, ["level","order"]);
                voFuncTree = _.sortBy(voFuncTree, function(item){
                  return item.level + "-" + item.order;
                });
                voMenuTree = _.sortBy(voMenuTree, function(item){
                  return item.level + "-" + item.order;
                });
                console.log("voMenuTree get:", voMenuTree);
                var voFuncTreeRtn = CommonUtil.Common_flatToTree(voFuncTree);
                var voMenuTreeRtn = CommonUtil.Common_flatToTree(voMenuTree);

                console.log("need resolve,voRtn", voFuncTreeRtn);
                voMenuTreeRtn = _.sortBy(voMenuTreeRtn,"order");
                //拼装model
                _self.set("modelPre.treedata",{children: voMenuTreeRtn});
                //把功能树放到全局服务
                _self.get("service_PageConstrut").set("funcTreeData",voFuncTree);
                console.log("need resolve tree model");
                resolve();
              }
            };
            privilegesIn.forEach(function (privilege) {
              console.log("privilege in forEach:", privilege);
              var voItem = {
                id: privilege.get("id"),
                text: privilege.get("showName"),
                icon: privilege.get("icon"),
                code: privilege.get("code"),
                type:privilege.get("type"),
                level:privilege.get("level"),
                order:privilege.get("order"),
              };
              if (privilege.get("level") === 1) {
                //第一级直接放入数组
                endTransfer(voItem);
              } else {
                //填入上级id
                privilege.get("parent").then((parent) => {
                  voItem.parentId = parent.get("id");
                  endTransfer(voItem);
                });
              }
            });
          });
        },function(){
          console.log("get role fail");
        });
      });
    });
  },
  gotoLoginPage: function(){
    this.transitionTo('user-login');
  },
  model(params,transition){
    var _self = this;
    console.log("modelPre.treedata:",this.get("modelPre.treedata"));

    this.get('store').query("dicttypetenant",{}).then(function(dicttypestenant){
      let Arr = new Ember.A();
      dicttypestenant.forEach(function(dicttype){
      dicttype.set("typegroupCode",dicttype.get("typegroupTenant.typegroupcode"));
        Arr.pushObject(dicttype);
      });
      _self.get('global_dataLoader').set("dicttypestenant",Arr);
    });
    var model = {treedata: this.get("modelPre.treedata")};
    return model;
  },
  setupController(controller, model){
    this._super(controller, model);
    console.log("model rtn:", model);
    // controller.set("model", model);
    //移动端底部菜单数据
    this.get("global_dataLoader").getMobileMenu().then(function(menus){
      console.log("need set menus",menus);
      controller.set("mobileMenus",menus);
    });
    //console.log("rtl",rtl);
  }
})
;
